<?php

/**
 * Description of UcetAdmin
 *
 * @author David Dusek
 */
class UcetAdminPresenter extends AdminPresenter {
    public function renderDefault() {
        $estateModel = new EstateModel($this->db);
        $referenceModel = new ReferenceModel($this->db);
        $this->template->offersCount = $estateModel->where("agent", $this->user->getId());
        $this->template->referenceCount = $referenceModel->where("agent", $this->user->getId());
    }
    
    public function renderZmenaFotky() {
        
    }
    
    public function renderZmenaHesla() {
        
    }
    
    protected function createComponentChangePictureForm() {
        $form = new NAppForm;
        $form->addUpload('picture', 'Nová fotka (512 x 683 px):')
                ->setRequired('Vyberte soubor s fotkou.');

        $form->addSubmit('send', 'Uložit');

        $form->onSuccess[] = $this->changePictureFormSubmitted;
        return $form;
    }
    
    /**
     * 
     *
     * @param NAppForm $form 
     */
    public function changePictureFormSubmitted($form) {
        try {
            $values = $form->getValues();

            $pictureFile = $values["picture"];
            if (!$pictureFile->isOk()) {
                throw new UserException("Soubor se nepodařilo nahrát. Zkuste to znovu.");
            }
            if ($pictureFile->isImage()) {
                $size = $pictureFile->getImageSize();
                if ($size[0] != 512 || $size[1] != 683) {
                    throw new UserException("Špatný rozměr obrázku. Nahrajte obrázek o velikost 512 x 683 pixelů.");
                }
                
                $dbName = "images/users/" . $pictureFile->getName();
                $fileSaved = $pictureFile->move(WWW_DIR . '/' . $dbName);                
                $thumb = NImage::fromFile($fileSaved->getTemporaryFile());
                $thumb->resize(64, NULL);
                $thumb->save(Picture::getThumbPath($fileSaved->getTemporaryFile()));
                
                $agentModel = new AgentModel($this->db);
                $user = $agentModel->get($this->user->getId());
                
                if ($user->picture != $dbName && $user->picture != "images/users/no-image.png") {
                    unlink(WWW_DIR . '/' . $user->picture);
                    unlink(Picture::getThumbPath(WWW_DIR . '/' . $user->picture));
                }
                
                $agentModel->where("id", $this->user->getId())->update(array("picture" => $dbName));
                $this->user->getIdentity()->__set("picture", $dbName);
            } else {
                throw new UserException("Nepodporovaný formát obrázku. Vyberte soubor ve formátu GIF, PNG nebo JPEG.");
            }
                
            $this->flashMessage("Fotka byla změněna");
            $this->redirect("default");
        } catch (UserException $e) {
            $form->addError($e->getMessage());
        }
    }    
    
    protected function createComponentChangePassForm() {
        $form = new NAppForm;
        $form->addPassword('oldPassword', 'Heslo:')
                ->setRequired('Staré heslo je povinné.');

        $form->addPassword('password', 'Nové heslo (min. 6 znaků):')
                ->setRequired('Nové heslo je povinné.')
                ->addRule(NForm::MIN_LENGTH, "Minimální délka hesla je 6 znaků", 6);
        
        $form->addPassword('passwordRep', 'Nové heslo znovu:')
                ->setRequired('Zopakování nového hesla je povinné.');

        $form->addSubmit('send', 'Změnit');

        $form->onSuccess[] = $this->changePassFormSubmitted;
        return $form;
    }
    
    /**
     * 
     *
     * @param NAppForm $form 
     */
    public function changePassFormSubmitted($form) {
        try {
            $values = $form->getValues();
        
            $agentModel = new AgentModel($this->db);            
            $user = $agentModel->get($this->user->getId());
                        
            if ($user === FALSE) { throw new UserException("Uživatel v systému neexistuje"); }            
            $oldPass = Authenticator::calculateHash($values["oldPassword"], $user->lastname);
            if ($oldPass !== $user->password) { throw new UserException("Špatně zadané aktuální heslo"); }
            if ($values["password"] !== $values["passwordRep"]) { throw new UserException("Zadaná hesla se neshodují"); }
            
            $newPass = Authenticator::calculateHash($values["password"], $user->lastname);
            $agentModel->where("id", $user->id)->update(array(
                "password" => $newPass));
            
            $this->flashMessage("Heslo bylo změněno");
            $this->redirect("default");
        } catch (UserException $e) {
            $form->addError($e->getMessage());
        }
    }
}
